/*
* 此控件只能在users.net114.com域下使用
* usage:
* $.imgUploader({
	containerid:'imgup',           //控件容器id 
	// dir:'uploads/user/11/03/',     //上传目录  默认为uploads/ 必须以uploads或importimg开头
	channel:'',       //频道  默认为空
	img_cnt_limit:5,               //最多上传图片张数 默认为10张
	max_file_size:1024,               //单张图片最大文件大小  单位为kb 默认为1024kb 0不限制
    prevent_duplicates:true,       //是否阻止上传相同图片 默认为true
	extensions:'jpg,jpeg,gif,png',  //图片扩展名 只能为,分隔的jpg,jpeg,gif,png之一 默认是全部
	multi_selection:true, //是否允许多选 默认为true
	min_img_width:0, //图片最小宽度 默认0为不限制 单位px
	min_img_height:0,  //图片最小高度 默认0为不限制 单位px
	single_file: false, //是否单文件 默认false
    include_imgname: false, //是否包含图片描述 默认false
    placeholder:'图片描述', //图片描述默认输入提示
    del_confirm: false,  //删除前是否弹出提示
	olds : {
		process_url:'',  //删除处理地址
		list:[
		     {filepath:'http://i1.ymfile.com/uploads/x1_1.1415241547_628_427_72363-100-100.jpg',id:1,imgname:''},
			 {filepath:'http://i1.ymfile.com/uploads/x1_1.1415246038_628_417_155780-100-100.jpg',id:2,imgname:''},
			 {filepath:'http://i1.ymfile.com/uploads/x1_1.1415246073_628_419_99914-100-100.jpg',id:3,imgname:''}
		]
		//图片地址 filepath是由imageSrcHandle生成100*100图片地址 该属性必须,其他根据情况自由添加参数
	}
	});
*
*/
;(function (global, $, undefined) {
	"use strict";
	if (!$) {
		throw "imgUploader requires jQuery"; // jQuery is not loaded.
	}
	if ($ && $.imgUploader && $.plupload) { return; } // ImgUploader is already loaded

	$("<link />").attr({ rel: "stylesheet",type: "text/css",href: "http://style.ymfile.com/css/plugs/imgupload/plupload.css"}).appendTo("head");
	function formatSize(size) {
			function round(num, precision) {
				return Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision);
			}
			var boundary = Math.pow(1024, 4);
			if (size >= boundary) {
				return round(size / boundary, 1) + "" + 'TB';
			}
			if (size >= (boundary/=1024)) {
				return round(size / boundary, 1) + "" + 'GB';
			}
			if (size >= (boundary/=1024)) {
				return round(size / boundary, 1) + "" + 'MB';
			}
			if (size >= 1024) {
				return Math.round(size / 1024) + "" + 'KB';
			}
			return size + "" + "B";
	}
    var uploader={};

	$.imgUploader = function (options) {
		var defaults = {
				img_cnt_limit: 5,  //图片总张数
				max_file_size: 1024,  //单张图片文件大小 单位kb
				prevent_duplicates: true, //阻止上传相同图片
				dir: '', //上传文件夹
				channel: '',
				extensions: 'jpg,jpeg,gif,png', //允许上传的文件扩展名
				containerid: "imgup", //控件容器id
				multi_selection: true, //是否允许多选
				min_img_width: 0,    //图片最小宽度 0为不限制
				min_img_height: 0,   //图片最小高度 0为不限制
				single_file: false, //是否单文件 默认false
                include_imgname: false, //是否有图片描述 默认false
                placeholder:'图片描述', //图片描述默认输入提示
				del_confirm: false, //删除前是否弹出提示                
				olds : {
					process_url: '',  //删除处理地址
					list: []
				}
			};
		var options = $.extend(defaults, options);
		if (options.single_file) {
			options.multi_selection=false;
			options.img_cnt_limit=1;
		}		
		var uploaded_cnt = 0;
		var total_cnt = 0;
		var max_file_cnt = options.img_cnt_limit;
		$('#'+options.containerid).append('<div class="uploader_clearfix uploader_pre-z" id="'+options.containerid+'_filelist" style="display: block;"></div>');
		var upaddimg = '<img src="http://i2.ymfile.com/images/images/overupimg.png" border=0 width="86" height="30"/>';
		if(window.location.hostname == 'me.net114.com') upaddimg='<img src="http://i2.ymfile.com/images/shop/me/img.gif" border=0 width="62" height="46"/>';
		
		var ht = '<div class="uploader_clearfix" id="'+options.containerid+'_container">';
            ht += '   <a href="javascript:void(0)" class="uploader_fl uploader_mr10 uploader_w_local" id="'+options.containerid+'_browsebtn">'+upaddimg+'</a><div class="uploader_clearfix"></div>    <span class="uploader_photo_tips">';
	    if (!options.single_file) ht += '<span id="'+options.containerid+'_upinfo" style="display: inline;">已上传图片<b class="uploader_green uploader_mlr2 uploader_upnum">'+uploaded_cnt+'</b>/<b class="uploader_c_666 uploader_mlr2 uploader_maxnum">'+total_cnt+'</b></span>';
		if (options.max_file_size)
		{
			if (!options.single_file) ht += '，';
			if (options.img_cnt_limit>1) ht += '每张';
			ht += '最大<span class="uploader_action_po_top">'+formatSize(options.max_file_size*1024)+'</span>';
		}
		if (!options.single_file)
		{
			ht += ',最多<span>'+options.img_cnt_limit+'</span>张';
		}
		if (options.extensions)
		{
			ht += ',支持<span>'+options.extensions.replace(/,/g,'、')+'</span>格式';
		}
		if (options.min_img_width)
		{
			ht += ',最小宽度:'+options.min_img_width+'px';
		}
		if (options.min_img_height)
		{
			ht += ',最小高度:'+options.min_img_height+'px';
		}
		 ht += '</span></div>';
		$('#'+options.containerid).append(ht);
        function initialize(plupload) {
		       plupload.addFileFilter('max_file_count', function(maxCount, file, cb) {
					if (!options.single_file && (maxCount <= this.files.length - (this.total.uploaded + this.total.failed))) {
						this.disableBrowse();
						/*
						this.trigger('Error', {
							code : -9001,
							message : "文件数量错误。",
							file : file
						});*/
						cb(false);
					} else {
						cb(true);
					}
				});
				 plupload.addFileFilter('min_img_width', function(minWidth, file, cb) {
				   if (!minWidth)
				   {
					   return cb(true);
				   }
				  var self = this, img = new o.Image(); 
				  function finalize(result) {
					img.destroy();
					img = null;
					if (!result) {
					  self.trigger('Error', {
						code : -9002,
						message : "图片宽度不能少于 " + minWidth,
						file : file
					  });     
					}
					cb(result);
				  } 
				  img.onload = function() {
					finalize(img.width  > minWidth);
				  }; 
				  img.onerror = function() {
					finalize(false);
				  };
				 
				  img.load(file.getSource());
			});
			plupload.addFileFilter('min_img_height', function(minHeight, file, cb) {
				if (!minHeight)
			   {
				   return cb(true);
			   }
			  var self = this, img = new o.Image(); 
			  function finalize(result) {
				img.destroy();
				img = null;
				if (!result) {
				  self.trigger('Error', {
					code : -9003,
					message : "图片高度不能少于 " + minHeight,
					file : file
				  });    
				}
				cb(result);
			  } 
			  img.onload = function() {
				finalize(img.width  > minHeight);
			  }; 
			  img.onerror = function() {
				finalize(false);
			  }; 
			  img.load(file.getSource());
			});
				uploader[options.containerid] = new plupload.Uploader({
				runtimes : 'html5,flash,silverlight,html4',
				browse_button : document.getElementById(options.containerid+'_browsebtn'),   // you can pass in id...
				container: document.getElementById(options.containerid+'_container'), // ... or DOM Element itself
				drop_element: document.getElementById(options.containerid+'_browsebtn'),
				url : '/uploadimg.html',
				multipart_params :{'dir':options.dir,'maxsize':options.max_file_size,'channel':options.channel},
				flash_swf_url : '/js/plupload/Moxie.swf',
				silverlight_xap_url : '/js/plupload//Moxie.xap',
                //urlstream_upload: true,
                max_retries:2,
                headers: {
                    Authorization: ""
                },
				multi_selection:options.multi_selection,		
				filters : {
					max_file_size : options.max_file_size+'kb',
					prevent_duplicates : options.prevent_duplicates,
					max_file_count:options.img_cnt_limit,
					mime_types: [
						{title : "Image files", extensions : options.extensions},
					],
					min_img_width : options.min_img_width,
					min_img_height : options.min_img_height
				},

				init: {
					PostInit: function() {
                        if (this.runtime=='flash') $(".moxie-shim-flash").css({"width":"85px","height":"29px"});      
						$('#'+options.containerid+'_filelist').empty();						
						var ofiles = options.olds.list,olen = ofiles.length;
						if (olen===0) return;						
						var ht='';
						for (var i=0; i<olen; i++)
						{
							var obj = ofiles[i];
							var filepath = obj.filepath, fileName = filepath.split('/').pop();
							var matches = fileName&&fileName.match(/\.([^.]+)$/), ext = matches?matches[1].toLowerCase():'';
							var filetype = (ext=='jpg'||ext=='jpeg'||ext=='jpe')?'image/jpeg':(ext=='gif'?'image/gif':(ext=='png'?'image/png':''));
							var filesize = fileName.split('.')[1].split('-')[0].split('_').pop() - 0;
							var file = {};
							file.name = fileName; file.type = filetype; file.size = filesize;
							file = new plupload.File(file);
							file.status = plupload.DONE; file.percent = 100; file.loaded = filesize; file.destroy = $.noop;	file.isold = true;
							this.files.push(file);
							this.total.size += filesize;
							this.total.loaded += filesize;
							
						
							
							//图片路径处理
							var $a = $('<a>', { 'href': filepath});
							var pathname = $a.prop('pathname');
							var imgparam = pathname.split('-');
							var plen = imgparam.length;
							var imgpath = imgparam[0];
							if(plen > 1){
								var imgsuffix = imgparam[plen-1].split('.');
								var strsuffix = imgsuffix[imgsuffix.length-1]
								var srcurl = imgpath+'.'+strsuffix;
							}else{
								var srcurl = imgpath;
							}
							
							var sp = srcurl; 
						
							obj.filepath = sp;
							
							
							ht += '<div class="uploader_imgbox">'+
								  '  <div class="uploader_w_upload">'+
								  '    <input type="hidden" value="0" name="'+options.containerid+'_tmpids[]"/>'+
								  '    <input type="hidden" value="'+plupload.xmlEncode(sp)+'" name="'+options.containerid+'_imgfiles[]"/>'+
								  '    <a title="删除" data-id="'+file.id+'" data-param="'+$.param(obj)+'" class="uploader_item_close" href="javascript:void(0)">删除</a>'+
								  '    <div class="uploader_item_box"><img src="'+filepath+'"></div>'+
								  '  </div>';
                                if (options.include_imgname)
                                {
                                    ht += '<input placeholder="'+options.placeholder+'" class="uploader_imgnames" name="'+options.containerid+'_imgnames[]" value="'+obj.imgname+'" />';
                                }
                                  
								  ht += '</div>';
							if (options.single_file) { //此处应该由服务器端保证
								olen=1;
								break;
							}
						}


                        $('#'+options.containerid+'_filelist').append(ht);
						this.total.percent = 100;
						this.total.uploaded = olen;
						this.refresh();
						!options.single_file && $('#'+options.containerid+'_upinfo').find("b:first").text(uploaded_cnt=olen);
						!options.single_file && $('#'+options.containerid+'_upinfo').find("b:eq(1)").text(total_cnt=olen);
					},

					FilesAdded: function(up, files) {
						up.disableBrowse(true);
						if (options.single_file) $('#'+options.containerid+'_filelist').find('.uploader_item_close').trigger('click');
						var toomany=false;
						plupload.each(files, function(file) {
						  if(total_cnt < max_file_cnt){
							      var ht = '<div class="uploader_imgbox uploader_loading">'+
										   '  <div class="uploader_w_upload">'+
									       '    <input type="hidden" value="0" name="'+options.containerid+'_tmpids[]"/>'+
										   '     <input type="hidden" name="'+options.containerid+'_imgfiles[]" value=""/><a href="javascript:void(0)" class="uploader_item_close" data-id="'+file.id+'" title="关闭">关闭</a>'+
										   '        <div class="uploader_wait_con">'+
										   '            <p class="uploader_pershow">上传中…</p>'+
										   '            <div class="uploader_wait_loading"><div style="width:0%" class="uploader_loading_progress"></div></div>'+
										   '        </div>'+
										   '   </div>';
                                            if (options.include_imgname)
                                            {
                                                ht += '<input placeholder="'+options.placeholder+'" class="uploader_imgnames" name="'+options.containerid+'_imgnames[]" />';
                                            }
										   ht +='</div>';
								  $('#'+options.containerid+'_filelist').append(ht);						 
								  !options.single_file && $('#'+options.containerid+'_upinfo').find("b:eq(1)").text(++total_cnt);                     
							} else {
								toomany=true; //超过图片数限制
								up.removeFile(file);
							}
						});
                        // if (files.length > max_file_cnt) {uploader[options.containerid].splice(); } // reset the queue to zero
                        $('#'+options.containerid).trigger('FilesAdded', [options.containerid]);
						if (toomany) alert('最多只能上传'+max_file_cnt+'张图片!');
                        //up.refresh();
						setTimeout(function(){up.start();}, 150);
					},

					UploadProgress: function(up, file) {
						$('#'+options.containerid+'_filelist').find(".uploader_item_close[data-id='"+file.id+"']").next().find('.uploader_loading_progress').css('width', file.percent + '%');
					},

					FileUploaded: function(up, file, res) {
						var info = $.parseJSON(res.response),closebtn = $('#'+options.containerid+'_filelist').find(".uploader_item_close[data-id='"+file.id+"']"),src='',tmpid=0;
						if (info!==null)
						{
							if (info.error!='') {
								alert(info.error);
							} else {
								src = info.src;
								tmpid = info.id;
							}
						}
						
						//图片路径处理
						var $a = $('<a>', { 'href': src});
						var pathname = $a.prop('pathname');
						var imgparam = pathname.split('-');
						var plen = imgparam.length;
						var imgpath = imgparam[0];
						if(plen > 1){
							var imgsuffix = imgparam[plen-1].split('.');
							var strsuffix = imgsuffix[imgsuffix.length-1]
							var srcurl = imgpath+'.'+strsuffix;
						}else{
							var srcurl = imgpath;
						}
						
						closebtn.attr('title','删除').html('删除').prev('input:hidden').val(plupload.xmlEncode(srcurl)).prev('input:hidden').val(tmpid);//100*100
						closebtn.next().attr('class','uploader_item_box').html('<img src="'+plupload.xmlEncode(src)+'"/>');
						closebtn.parent().parent().removeClass('uploader_loading');
						!options.single_file && $('#'+options.containerid+'_upinfo').find("b:first").text(++uploaded_cnt);				
					},

					Error: function(up, err) {
						var ii= {
							e100 : '出现通用错误。',
							e200 : '出现Http错误。',
							e300 : '出现IO错误。',
							e400 : '出现安全认证错误。',
							e500 : '出现控件初始化错误。',
							e600 : '文件大小不能超过'+formatSize(options.max_file_size*1024),
							e601 : '出现选择文件类型不匹配错误。',
							e602 : '该文件已上传',
							e700 : '出现选择图片格式不匹配错误。',
							e701 : '出现选择图片内存问题。',
							e702 : '出现选择图片尺寸不匹配错误。',
							e9001 : '文件数量错误。',
							e9002 : '图片宽度不能少于'+options.min_img_width+'px。',
							e9003 : '图片高度不能少于'+options.min_img_height+'px。'
						}; 
						if(up.runtime!=''){
							alert('上传文件："' + err.file.name + '" ' + ii['e'+(0-err.code)]+'v2.3');
						}
						return false;
						//document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
					},
					UploadComplete: function(up) {
						//enable submit
						$('#'+options.containerid).trigger('UploadComplete', [options.containerid]);
						up.disableBrowse(false);
                        if (this.runtime=='flash') $(".moxie-shim-flash").css({"width":"85px","height":"29px"});
					}
				}
			});
			uploader[options.containerid].init();
            

			 $('#'+options.containerid).on('click','.uploader_item_close',function(e) {
				 if (options.del_confirm&&!confirm("您确定要删除该图片?"))
				 {
					 return false;
				 }
				 var fileid = $(this).attr('data-id');
				 var file = uploader[options.containerid].getFile(fileid);
				 uploader[options.containerid].removeFile(fileid);				 
				 if (file.isold)
				 {
					 var url=options.olds.process_url;
					 if(url) {
						 $.post(url, $(this).attr('data-param'));
					 } else {
						 var filepath = $('#'+options.containerid+'_filelist').find(".uploader_item_close[data-id='"+file.id+"']").prev("input:hidden").val();
						 $('<input type="hidden" name="'+options.containerid+'_delfiles[]" />').val(plupload.xmlEncode(filepath)).appendTo($('#'+options.containerid));						 
					 }
					 !options.single_file && $('#'+options.containerid+'_upinfo').find("b:first").text(--uploaded_cnt);	
				 } else if (file.percent==100)
				 {
                     var  imgfile_input = $('#'+options.containerid+'_filelist').find(".uploader_item_close[data-id='"+file.id+"']").prev("input:hidden");
					 $.post("/uploadimg-cmd-del.html",{filepath:imgfile_input.val(),id:imgfile_input.prev("input:hidden").val()});
					 !options.single_file && $('#'+options.containerid+'_upinfo').find("b:first").text(--uploaded_cnt);				 
				 }
				 file.destroy();				
				 !options.single_file && $('#'+options.containerid+'_upinfo').find("b:eq(1)").text(--total_cnt);
			     $(this).parent().parent().remove();
				 $('#'+options.containerid).trigger('FileDeleted', [options.containerid]);
                 if (uploader[options.containerid].runtime=='flash') $(".moxie-shim-flash").css({"width":"85px","height":"29px"});
				 e.preventDefault();
		    });

		}
        if ($.plupload)
        {
            initialize($.plupload);
        } else {
	        $.when($.getScript("http://js.ymfile.com/js/plupload/plupload.full.min.js")).done(function(){
                $.plupload=plupload;
                initialize(plupload);
             });
        }
		
	};
})(this, this.jQuery);